package sddz.foodmanage.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.activity.LoginActivity;
import sddz.foodmanage.adapter.InpurchaingAdapter;
import sddz.foodmanage.base.BaseFragment;
import sddz.foodmanage.model.InpurchaingBean;
import sddz.foodmanage.model.SelectOkBean;
import sddz.foodmanage.model.UserStatusBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.DoubleUtil;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.MyUtils;
import sddz.foodmanage.utils.SpfUtils;
import sddz.foodmanage.utils.StatusBarCompat;

import static android.widget.Toast.LENGTH_SHORT;

/**
 * @Date:2019/7/3
 * @Author:lbb 采购中
 */
public class InpurchasingFragment extends BaseFragment implements InpurchaingAdapter.ModifyCountInterface {

    private TimePickerView pvDeliveryTime;  //配送时间选择器
    private String deliverTime;//配送时间
    @BindView(R.id.delivery_time)
    TextView tvdeliverTime;
    @BindView(R.id.tv_deliver_time)
    TextView tvDeliverTime;
    private int dinner_num;//用餐人数
    @BindView(R.id.tv_dinner_num)
    TextView tvDinnerNum;
    @BindView(R.id.et_dinner_num)
    EditText etDinnerNum;

    @BindView(R.id.title_navigation_icon)
    ImageView titleNavigationIcon;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.title_menu_icon)
    ImageView titleMenuIcon;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.image_title_right)
    ImageView imageTitleRight;
    Unbinder unbinder;
    @BindView(R.id.news_listView)
    ListView newsListView;

    @BindView(R.id.tv_xiaorder)
    TextView tvXiaorder;
    @BindView(R.id.tv_nodata)
    TextView tvNodata;
    @BindView(R.id.title_layout)
    AppBarLayout titleLayout;
    @BindView(R.id.tv_totalprice)
    TextView tvTotalprice;
    @BindView(R.id.news_trl)
    AutoLinearLayout newsTrl;

    private List<InpurchaingBean.DataBean.GoodsBean> goodsList = new ArrayList<>();
    InpurchaingBean inpurchaing = new InpurchaingBean();
    private InpurchaingAdapter inpurchaingadapter = new InpurchaingAdapter();
    //==============================================================================================
    //用于给每个订单加备注
    public List<String> goods_remark_list = new ArrayList<>();

    //==============================================================================================
    public InpurchasingFragment() {
        // Required empty public constructor
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_inpurchasing, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initData();
        initListener();
        view.setClickable(true);
        return view;
    }


    private void initListener() {
        if (inpurchaingadapter != null) {
            inpurchaingadapter.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.e("onActivityCreated", "onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e("onStart", "onStart");

    }

    @Override
    public void onResume() {
        super.onResume();
        getInpurchasing();
        Log.e("onResume", "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("onPause", "onPause");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.e("onSaveInstanceState", "onSaveInstanceState");
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setStatusBar();
            getInpurchasing();
        }
    }

    private void setStatusBar() {
        StatusBarCompat.setStatusBarColor(getActivity(), mActivity.getResources().getColor(R.color.colorPrimary));
    }

    private void initData() {
        getInpurchasing();
    }

    /**
     * 获取采购中数据
     */
    private void getInpurchasing() {
        baseDialog.show();
        HttpUtils.getInstance().GET(mActivity, API.getInpurchasing, SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                Log.e("获取采购中数据：", body);
                baseDialog.dismiss();
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (code == 200) {
                            if (goodsList != null) {
                                goodsList.clear();
                            }
                            if (jsonObject.optJSONObject("data") != null) {
                                inpurchaing = new Gson().fromJson(body, InpurchaingBean.class);
                                if (inpurchaing.getData().getGoods() != null) {
                                    goodsList.addAll(inpurchaing.getData().getGoods());
                                    //==============================================================================================
                                    //用于给每个订单加备注 初始化每条备注信息为空信息
                                    for (int i = 0; i < goodsList.size(); i++) {
                                        goods_remark_list.add("");
                                    }
                                    //==============================================================================================

                                    if (goodsList.size() > 0) {
                                        newsListView.setVisibility(View.VISIBLE);
                                        inpurchaingadapter.setdata(mActivity, goodsList, goods_remark_list);
                                        newsListView.setAdapter(inpurchaingadapter);
                                        tvNodata.setVisibility(View.GONE);
                                        tvXiaorder.setVisibility(View.VISIBLE);
                                        tvTotalprice.setVisibility(View.VISIBLE);
                                        tvdeliverTime.setVisibility(View.VISIBLE);
                                        tvDeliverTime.setVisibility(View.VISIBLE);
                                        tvDinnerNum.setVisibility(View.VISIBLE);
                                        etDinnerNum.setVisibility(View.VISIBLE);
                                    } else {
                                        newsListView.setVisibility(View.GONE);
                                        tvNodata.setVisibility(View.VISIBLE);
                                        tvXiaorder.setVisibility(View.GONE);
                                        tvTotalprice.setVisibility(View.GONE);
                                        tvdeliverTime.setVisibility(View.GONE);
                                        tvDeliverTime.setVisibility(View.GONE);
                                        tvDinnerNum.setVisibility(View.GONE);
                                        etDinnerNum.setVisibility(View.GONE);
                                    }
                                }
                                tvTotalprice.setText("小计:" + inpurchaing.getData().getTotal_price() + "元");
                            } else {
                                newsListView.setVisibility(View.GONE);
                                tvNodata.setVisibility(View.VISIBLE);
                                tvXiaorder.setVisibility(View.GONE);
                                tvTotalprice.setVisibility(View.GONE);
                                tvdeliverTime.setVisibility(View.GONE);
                                tvDeliverTime.setVisibility(View.GONE);
                                tvDinnerNum.setVisibility(View.GONE);
                                etDinnerNum.setVisibility(View.GONE);
                            }

                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            getInpurchasing();
                        } else if (code == 401) {
                            show(jsonObject.optString("message"));
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            mActivity.finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {
                baseDialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });
    }

    private void initView() {
        titleNavigationIcon.setVisibility(View.GONE);
        titleText.setText("采购中");
        //初始化时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String sim = dateFormat.format(date);
        deliverTime = sim;
        tvDeliverTime.setText(sim);
        //时间选择器
        pvDeliveryTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String date1 = new SimpleDateFormat("yyyy-MM-dd").format(date);
                deliverTime = date1;
                tvDeliverTime.setText(deliverTime);
            }
        }).setType(new boolean[]{true, true, true, false, false, false}).setCancelColor(getResources().getColor(R.color.gray_text))
                .setSubmitColor(getResources().getColor(R.color.title_color)).build();

        pvDeliveryTime.setDate(Calendar.getInstance());

//        ProgressLayout progressLayout = new ProgressLayout(mActivity);
//        progressLayout.setColorSchemeResources(R.color.colorPrimary);
//        newsTrl.setHeaderView(progressLayout);
        //初始化时间选择器
        //时间选择器的点击事件

        //用餐人数数据初始化
        UserStatusBean.DataBean.UserBean userData = SpfUtils.getUserData(getContext());
        dinner_num = userData.getDinner_num();
        etDinnerNum.setText(userData.getDinner_num()+"");
        etDinnerNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                try {
                    dinner_num = Integer.valueOf(editable.toString());
                    Log.i("dinner_num", "afterTextChanged: "+dinner_num);
                }catch (Exception e){
                    if(!editable.toString().equals("")){
                        Toast.makeText(getContext(),"请输入正确格式的数据", LENGTH_SHORT).show();
                        String s = String.valueOf(dinner_num);
                        etDinnerNum.setText(s);
                        etDinnerNum.setSelection(s.length());//将光标移至文字末尾
                    }
                    Log.i("e", "afterTextChanged: "+e.toString());
                }
            }
        });
    }

    /**
     * 下单
     */
    private void xiadan() {
        SelectOkBean selectok = new SelectOkBean();
        selectok.setDelivery(deliverTime);//设置送货时间
        String s = etDinnerNum.getText().toString();
        if(s.equals("")){
            Toast.makeText(getContext(),"请输入用餐人数", LENGTH_SHORT).show();
            return;
        }
        selectok.setDinner_num(dinner_num);//设置用餐人数
        List<SelectOkBean.DataBean> selectoklist = new ArrayList<>();
        for (int q = 0; q < goodsList.size(); q++) {
            SelectOkBean.DataBean databean = new SelectOkBean.DataBean();
            databean.setId(goodsList.get(q).getId());
            databean.setAmount(goodsList.get(q).getAmount() + "");
            databean.setRemark(goods_remark_list.get(q));
            selectoklist.add(databean);
        }
        selectok.setData(selectoklist);
        Log.e("selectok", JSON.toJSONString(selectok));
        baseDialog.show();
        HttpUtils.getInstance().POST(mActivity, API.getxiaorder, JSON.toJSONString(selectok), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                baseDialog.dismiss();
                Log.e("下单结果", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (!jsonObject.optString("message").equals("")) {
                            show(jsonObject.optString("message"));
                        }
                        if (code == 200) {
                            show("下单成功");
                            tvXiaorder.setVisibility(View.GONE);
                            newsListView.setVisibility(View.GONE);
                            tvdeliverTime.setVisibility(View.GONE);
                            tvDeliverTime.setVisibility(View.GONE);
                            tvDinnerNum.setVisibility(View.GONE);
                            etDinnerNum.setVisibility(View.GONE);
                            tvNodata.setVisibility(View.VISIBLE);
                            tvTotalprice.setVisibility(View.GONE);
                            goodsList.clear();
                            goods_remark_list.clear();
                            inpurchaingadapter.notifyDataSetChanged();
                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            xiadan();
                        } else if (code == 401) {
                            show(jsonObject.optString("message"));
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            mActivity.finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Request error, Exception e) {
                baseDialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void doIncrease(View showCountView, int position) {
        Log.e("jia", ((TextView) showCountView).getText().toString());
        Double add = DoubleUtil.add(Double.parseDouble(((TextView) showCountView).getText().toString()), Double.parseDouble("1"));
        ((TextView) showCountView).setText(add + "");
        goodsList.get(position).setAmount(add);
        Double he = 0.0;
        for (int i = 0; i < goodsList.size(); i++) {
            Double goodprice = DoubleUtil.mul(Double.parseDouble(goodsList.get(i).getPrice()), goodsList.get(i).getAmount());
            he = DoubleUtil.add(he, goodprice);
        }
        tvTotalprice.setText("小计:" + he + "元");
    }

    /**
     * 减
     *
     * @param showCountView 用于展示变化后数量的View
     * @param position
     */
    @Override
    public void doDecrease(final View showCountView, final int position) {
        Double currentCount = Double.parseDouble(((TextView) showCountView).getText().toString());
        if (currentCount <= 1.0) {

            AlertDialog alertDialog2 = new AlertDialog.Builder(mActivity)
                    .setMessage("确定要删除商品吗")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Double jian = DoubleUtil.sub(Double.parseDouble(((TextView) showCountView).getText().toString()), Double.parseDouble("1"));
                            ((TextView) showCountView).setText(0 + "");
                            goodsList.remove(position);
                            inpurchaingadapter.notifyDataSetChanged();
                            Double he = 0.0;
                            for (int a = 0; a < goodsList.size(); a++) {
                                Double goodprice = DoubleUtil.mul(Double.parseDouble(goodsList.get(a).getPrice()), goodsList.get(a).getAmount());
                                he = DoubleUtil.add(he, goodprice);
                            }
                            tvTotalprice.setText("小计:" + he + "元");

                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                        }
                    })
                    .create();
            alertDialog2.show();

            return;
        }
        Double jian = DoubleUtil.sub(Double.parseDouble(((TextView) showCountView).getText().toString()), Double.parseDouble("1"));
        ((TextView) showCountView).setText(jian + "");
        goodsList.get(position).setAmount(jian);
        Double he = 0.0;
        for (int i = 0; i < goodsList.size(); i++) {
            Double goodprice = DoubleUtil.mul(Double.parseDouble(goodsList.get(i).getPrice()), goodsList.get(i).getAmount());
            he = DoubleUtil.add(he, goodprice);
        }
        tvTotalprice.setText("小计:" + he + "元");
    }

    @Override
    public void doTextView(final View showCountView, final int position) {
        final EditText inputServer = new EditText(mActivity);
        inputServer.setHint("请输入重量");
        inputServer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        inputServer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setView(inputServer)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (TextUtils.isEmpty(inputServer.getText().toString())) {//如果数量 为0，移除数据
                    ((TextView) showCountView).setText("0");
                    Log.e("空", "");
                    if (goodsList != null) {
                        if (goodsList.size() > 0) {
                            for (int z = 0; z < goodsList.size(); z++) {
                                goodsList.remove(z);
                            }
                        }
                    }

                }
                if (MyUtils.isDoubleOrFloat(inputServer.getText().toString())) {
                    ((TextView) showCountView).setText(inputServer.getText().toString());
                    if (goodsList != null) {
                        if (goodsList.size() > 0) {
//                            Log.e("修改为",inputServer.getText().toString() );
                            goodsList.get(position).setAmount(Double.parseDouble(inputServer.getText().toString()));
//                            Log.e("修改后为：",  goodsList.get(position).getAmount());

                        }
                    } else {
                        ((TextView) showCountView).setText("0");//输入的数量不是double类型的，也默认为0，移除数据
                        if (goodsList != null) {
                            if (goodsList.size() > 0) {
                                goodsList.remove(position);
                            }
                        }
                    }
                }
                Double he = 0.0;
                for (int i = 0; i < goodsList.size(); i++) {
//                    Log.e("修改后的重量：",Double.parseDouble(goodsList.get(i).getAmount())+"");
                    Double goodprice = DoubleUtil.mul(Double.parseDouble(goodsList.get(i).getPrice()), goodsList.get(i).getAmount());
                    he = DoubleUtil.add(he, goodprice);
                }
                tvTotalprice.setText("小计:" + he + "元");
            }
        });
        builder.show();

    }

    @Override
    public void doDelect(View showCountView, final int position) {

        AlertDialog alertDialog2 = new AlertDialog.Builder(mActivity)
                .setMessage("确定要删除商品吗")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        goodsList.remove(position);

                        inpurchaingadapter.notifyDataSetChanged();
                        Log.e("goodsList", goodsList.size() + "");
                        Double he = 0.0;
                        for (int b = 0; b < goodsList.size(); b++) {
                            Double goodprice = DoubleUtil.mul(Double.parseDouble(goodsList.get(b).getPrice()), goodsList.get(b).getAmount());
                            he = DoubleUtil.add(he, goodprice);
                        }
                        tvTotalprice.setText("小计:" + he + "元");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                })
                .create();
        alertDialog2.show();

    }

    @OnClick({R.id.tv_xiaorder, R.id.tv_deliver_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_xiaorder://下单
                xiadan();
                break;
            case R.id.tv_deliver_time://选择时间
                Log.i("clc", "请选择时间");
                pvDeliveryTime.show();
                break;
        }
    }

    //设置送货时间 用于在每次进入采购中页面时将送货时间改为当下
    public void setTvDeliverTime(String time){
        deliverTime = time;
        tvDeliverTime.setText(time);
    }


}
